import * as step from '@ali/flow-step-toolkit'
import * as util from './util'
import OSS from 'ali-oss'
import path from 'node:path'
import * as fs from 'fs'
import {UploadInputs} from './upload-inputs'

class CustomError extends Error {
    constructor(msg: string) {
        super(msg)
    }
}
export const customErrorInstance = new CustomError(
    'An error occurred when upload to OSS.'
)
export const authErrorInstance = new CustomError(
    'Access denied by authorizer policy for OSS.'
)

export async function put(artifact: UploadInputs) {
    artifact.repoId = ''
    if (artifact.fileId === undefined) {
        step.error("Failed to get params 'FILE_ID'")
        throw new Error("missing params 'FILE_ID'")
    }
    artifact.fileId =
        path.dirname(artifact.fileId) + '/' + artifact.artifactName
    let endpoint = await util.getEndpoint()
    if (
        artifact.accessKeyId === undefined ||
        artifact.accessKeySecret === undefined
    ) {
        step.error('Access Denied for undefined as/sk')
        throw new Error('Access Denied for undefined as/sk')
    }
    const client = new OSS({
        endpoint: endpoint,
        accessKeyId: artifact.accessKeyId,
        accessKeySecret: artifact.accessKeySecret,
        bucket: artifact.bucketName,
        stsToken: artifact.token
    })

    try {
        artifact.fileParentId = path.dirname(artifact.fileId)
        const result = await client.put(
            artifact.fileId,
            artifact.artifactFullName
        )
        //输出写入params
        const artifactUrl = process.env['ARTIFACT_URL']
        let packagePath = `execution-component&bucketName=${artifact.bucketName}&fileId=${artifact.fileId}&artifactName=${artifact.artifactName}`
        let artifactSource = 'system-oss'
        let output = `${process.env['stepIdentifier']}.ARTIFACT={"ARTIFACT_URL":"${artifactUrl}","ARTIFACT_NAME":"${artifact.artifactName}","ARTIFACT_MD5":"${artifact.fileMD5}","WEB_DOWNLOAD_URL":"${packagePath}","artifact":"${artifact.artifactName}","type":"flowPublic","downloadUrl":"${result.url}","md5":"${artifact.fileMD5}"}`
        let packageInfo = `PACKAGE_INFO={"packageLabel":"${artifact.artifact}","packagePath":"${packagePath}","uploadType":"${artifact.uploadType}","repoId":"${artifact.repoId}"}`
        let artifacts = `{"source":"${artifactSource}","type":"package","packageLabel":"${artifact.artifact}","objectKey": "${artifact.fileId}","bucketName": "${artifact.bucketName}","webDownloadURL":"${packagePath}","objectKeyPrefix":"${artifact.fileParentId}","name":"${artifact.artifact}","version":"${artifact.artifactVersion}","repoId":"${artifact.repoId}","fileSize":0}`
        step.addOutput(output);
        step.addOutput(packageInfo);
        step.addOutput(`ARTIFACTS=` + `[${artifacts}]`);
        // fs.writeFileSync(
        //     `${artifact.workDir}${util.SEP}params`,
        //     output + util.EOL,
        //     {flag: 'a'}
        // )
        // fs.appendFileSync(
        //     `${artifact.workDir}${util.SEP}params`,
        //     packageInfo + util.EOL
        // )
        // fs.appendFileSync(
        //     `${artifact.workDir}${util.SEP}params`,
        //     `ARTIFACTS=` + `[${artifacts}]` + util.EOL
        // )
        step.info(`Artifact download URL is: ${result.url}`)
        fs.unlinkSync(artifact.artifactFullName)
    } catch (e) {
        fs.unlinkSync(artifact.artifactFullName)
        throw customErrorInstance
    }
}
